<template>
  <el-form
    ref="formRef"
    :model="formData"
    :rules="formRules"
    v-loading="formLoading"
    label-width="0px"
    :inline-message="true"
  >
    <el-table :data="formData" class="-mt-10px">
      <el-table-column label="序号" type="index" width="60" />
      <el-table-column label="产品" min-width="200">
        <template #default="{ row, $index }">
          <el-form-item :prop="`${$index}.productId`" :rules="formRules.productId" class="mb-0px!">
            <select-single-product v-model:product-id="row.productId" v-model:product-name="row.productName" @selected="selectedProduct($event, row)" />
          </el-form-item>
        </template>
      </el-table-column>
      <el-table-column label="仓库" min-width="200">
        <template #default="{ row, $index }">
          <el-form-item :prop="`${$index}.warehouseId`" :rules="formRules.warehouseId" class="mb-0px!">
            <select-single-warehouse v-model:warehouse-id="row.warehouseId" v-model:position-id="row.positionId"/>
          </el-form-item>
        </template>
      </el-table-column>
      <el-table-column label="业务数量" min-width="150">
        <template #default="{ row, $index }">
          <el-form-item :prop="`${$index}.businessQty`" :rules="formRules.businessQty" class="mb-0px!">
            <el-input v-model="row.businessQty" placeholder="请输入业务数量" />
          </el-form-item>
        </template>
      </el-table-column>
      <el-table-column label="单位" min-width="150">
        <template #default="{ row, $index }">
          <el-form-item :prop="`${$index}.unitId`" :rules="formRules.unitId" class="mb-0px!">
            <select-single-unit v-model:unit-id="row.unitId" v-model:unit-name="row.unitName" disabled />
          </el-form-item>
        </template>
      </el-table-column>
      <el-table-column label="单位成本" min-width="150">
        <template #default="{ row, $index }">
          <el-form-item :prop="`${$index}.unitAmt`" :rules="formRules.unitAmt" class="mb-0px!">
            <el-input v-model="row.unitAmt" placeholder="请输入单位成本" />
          </el-form-item>
        </template>
      </el-table-column>
      <el-table-column label="成本金额" min-width="150">
        <template #default="{ row, $index }">
          <el-form-item :prop="`${$index}.costAmt`"  class="mb-0px!">
            <el-input :value="row.unitAmt * row.businessQty" placeholder="请输入成本金额" disabled />
          </el-form-item>
        </template>
      </el-table-column>
<!--      <el-table-column label="批次号" min-width="200">
        <template #default="{ row, $index }">
          <el-form-item :prop="`${$index}.batchNo`" :rules="formRules.batchNo" class="mb-0px!">
            <el-input v-model="row.batchNo" placeholder="请输入批次号" />
          </el-form-item>
        </template>
      </el-table-column>
      <el-table-column label="序列号" min-width="200">
        <template #default="{ row, $index }">
          <el-form-item :prop="`${$index}.serialNo`" :rules="formRules.serialNo" class="mb-0px!">
            <el-input v-model="row.serialNo" placeholder="请输入序列号" />
          </el-form-item>
        </template>
      </el-table-column>-->
      <el-table-column label="备注" min-width="200">
        <template #default="{ row, $index }">
          <el-form-item :prop="`${$index}.remark`" :rules="formRules.remark" class="mb-0px!">
            <el-input v-model="row.remark" placeholder="请输入备注" />
          </el-form-item>
        </template>
      </el-table-column>
      <el-table-column align="center" fixed="right" label="操作" width="60">
        <template #default="{ $index }">
          <el-button @click="handleDelete($index)" link>—</el-button>
        </template>
      </el-table-column>
    </el-table>
  </el-form>
  <el-row justify="center" class="mt-3">
    <el-button @click="handleAdd" round>+ 添加入库明细</el-button>
  </el-row>
</template>
<script setup lang="ts">
import * as OtherInApi from '@/api/wms/otherin'
import * as ProductWarehouseApi from '@/api/base/productwarehouse'
import {getProductWarehouseByProduct} from "@/api/base/productwarehouse";
import SelectSingleProduct from "@/views/base/productinfo/components/SelectSingleProduct.vue";
import SelectSingleWarehouse from "@/views/wms/warehouse/components/SelectSingleWarehouse.vue";
import SelectSingleUnit from "@/views/base/unit/components/SelectSingleUnit.vue";

const props = defineProps<{
  headId: undefined // 单头（主表的关联字段）
}>()
const formLoading = ref(false) // 表单的加载中
const formData = ref([])
const formRules = reactive({
  headId: [{ required: true, message: '单头不能为空', trigger: 'blur' }],
  productId: [{ required: true, message: '产品不能为空', trigger: 'blur' }],
  warehouseId: [{ required: true, message: '仓库不能为空', trigger: 'blur' }],
  businessQty: [{ required: true, message: '业务数量不能为空', trigger: 'blur' }],
  unitId: [{ required: true, message: '单位不能为空', trigger: 'blur' }],
})
const formRef = ref() // 表单 Ref

/** 监听主表的关联字段的变化，加载对应的子表数据 */
watch(
  () => props.headId,
  async (val) => {
    // 1. 重置表单
    formData.value = []
    // 2. val 非空，则加载数据
    if (!val) {
      return;
    }
    try {
      formLoading.value = true
      formData.value = await OtherInApi.getOtherInDListByHeadId(val)
    } finally {
      formLoading.value = false
    }
  },
  { immediate: true }
)

/** 新增按钮操作 */
const handleAdd = () => {
  const row = {
    id: undefined,
    headId: undefined,
    productId: undefined,
    warehouseId: undefined,
    positionId: undefined,
    businessQty: 0,
    unitId: undefined,
    unitAmt: 0,
    costAmt: 0,
    batchNo: undefined,
    serialNo: undefined,
    remark: undefined,
  }
  row.headId = props.headId
  formData.value.push(row)
}

/** 删除按钮操作 */
const handleDelete = (index) => {
  formData.value.splice(index, 1)
}

/** 产品选中事件*/
const selectedProduct = (data, row) => {
  if (data) {
    //获取产品仓库信息
    ProductWarehouseApi.getProductWarehouseByProduct(data.id).then(response=> {
      if (!response || response.status === 1){
        row.productId = undefined;
        ElMessage.error('未找到产品仓储信息')
        return;
      }
      row.warehouseId = response.inWarehouse;
      row.positionId = response.inPosition;
      row.unitId = data.unitId;
      row.unitName = data.unitName;
    })
  }
}

/** 表单校验 */
const validate = () => {
  return formRef.value.validate()
}

/** 表单值 */
const getData = () => {
  return formData.value
}

defineExpose({ validate, getData })
</script>
